import { BrowserWindow, Menu, Tray, app, ipcMain, nativeImage, shell } from 'electron';
import path from 'path';
import { fileURLToPath } from 'node:url';
import { saveWindow } from './windowProxy';
import store from './store';
const __dirname = path.dirname(fileURLToPath(import.meta.url));

export const LOGIN_WIDTH = 300;
export const LOGIN_HEIGHT = 370;
export const REGISTER_HEIGHT = 490;

// The built directory structure
//
// ├─┬─┬ dist
// │ │ └── index.html
// │ │
// │ ├─┬ dist-electron
// │ │ ├── main.js
// │ │ └── preload.mjs
// │
process.env.APP_ROOT = path.join(__dirname, '..')

// 🚧 Use ['ENV_NAME'] avoid vite:define plugin - Vite@2.x
export const VITE_DEV_SERVER_URL = process.env['VITE_DEV_SERVER_URL']
export const MAIN_DIST = path.join(process.env.APP_ROOT, 'dist-electron')
export const RENDERER_DIST = path.join(process.env.APP_ROOT, 'dist')

process.env.VITE_PUBLIC = VITE_DEV_SERVER_URL ? path.join(process.env.APP_ROOT, 'public') : RENDERER_DIST
export function createWindow(): BrowserWindow {
  const iconPath = path.join(process.env.VITE_PUBLIC || '', 'logo.jpg');

  const mainWindow = new BrowserWindow({
    width: LOGIN_WIDTH,
    height: LOGIN_HEIGHT,
    icon: path.join(process.env.VITE_PUBLIC || '', 'logo.jpg'),
    fullscreen: false,
    maximizable: false,
    // transparent: true,//创建一个完全透明的窗口
    titleBarStyle: 'hidden',
    resizable: false,//自动拖动大小
    autoHideMenuBar: true,//隐藏菜单
    hasShadow: true,
    webPreferences: {
      preload: path.join(__dirname, 'preload.mjs'),
      contextIsolation: true,
    },
    frame: false,
  });

  // 保存当前窗口实例
  saveWindow('main', mainWindow)

  //打开控制台
  if (process.env.NODE_ENV === 'development') {
    mainWindow.webContents.openDevTools();
  }

  mainWindow.on('ready-to-show', () => {
    mainWindow.show()
    mainWindow.setTitle("微信")
  })

  mainWindow.once('focus', () => mainWindow.flashFrame(false));

  mainWindow.on('close', (event) => {
    event.preventDefault();
    mainWindow.hide(); // 隐藏窗口
  });

  mainWindow.webContents.setWindowOpenHandler((details) => {
    shell.openExternal(details.url)
    return { action: 'deny' }
  })

  let loadURL = process.env.VITE_DEV_SERVER_URL || path.join(__dirname, '..', 'dist', 'index.html');
  loadURL = `${loadURL}#/`;
  if (process.env.VITE_DEV_SERVER_URL) {
    mainWindow.loadURL(loadURL);
  } else {
    mainWindow.loadFile(loadURL);
  }

  // mainWindow.webContents.openDevTools(); // 开发时启用

  // 创建系统托盘
  const tray = new Tray(nativeImage.createFromPath(iconPath));
  const contextMenu = [
    {
      label: '显示窗口',
      click: () => {
        mainWindow.show();
      },
    },
    {
      label: '退出',
      click: () => {
        mainWindow.destroy();
        app.quit();
      },
    },
  ]

  tray.setToolTip('微信');
  tray.setContextMenu(Menu.buildFromTemplate(contextMenu));

  // 点击托盘图标，显示主窗口
  tray.on("click", () => {
    mainWindow.setSkipTaskbar(false);
    mainWindow.show();
  });

  //设置本地store存储
  ipcMain.handle('onSetLocalStore', (_, ...args: any) => {
    const [key, value] = args;
    store.setData(key, value);
  });

  // TODO 获取本地存储

  // 登录注册
  ipcMain.handle('onLoginSuccess', (_, ...args: any) => {
    const [config] = args;
    // TODO 添加本地用户配置

    store.initUserId(config.uid);
    store.setUserData('token', config.token);

    mainWindow.setResizable(true);
    mainWindow.setSize(1195, 710);
    mainWindow.center();
    mainWindow.setMaximizable(true);
    mainWindow.setMinimumSize(700, 500);

    // 设置用户
    contextMenu.unshift({
      label: `用户：${config.nickname}`,
      click: () => {
        console.log('点击了用户。。。');
      }
    });
    tray.setContextMenu(Menu.buildFromTemplate(contextMenu));

    // TODO 初始化websocket
  });


  // 登录注册切换
  ipcMain.handle('onLoginOrRegister', (_, ...args: any) => {
    const [isLogin] = args;
    mainWindow.setResizable(true);
    if (isLogin) {
      mainWindow.setSize(LOGIN_WIDTH, LOGIN_HEIGHT);
    } else {
      mainWindow.setSize(LOGIN_WIDTH, REGISTER_HEIGHT);
    }
    mainWindow.setResizable(false);
  })

  // 监听窗口变化
  ipcMain.handle('winTitleOp', (event, ...args: any) => {
    const [action, data] = args;
    const webContents = event.sender;
    const win = BrowserWindow.fromWebContents(webContents)

    // 判断action
    switch (action) {
      case 'close':
        // 判断是哪种关闭方式
        if (data.closeType == 0) {
          win?.close();
        } else {
          win?.setSkipTaskbar(true) // 使窗口不显示在任务栏中
          win?.hide()
        }
        break;

      case 'minimize':
        win?.minimize();
        break;

      case 'maximize':
        win?.maximize();
        break;

      case 'unmaximize':
        win?.unmaximize();
        break;

      case 'top':
        win?.setAlwaysOnTop(data.top);
        break;
    }
  });

  // 处理添加好友
  ipcMain.handle('onAddToContact', (_, ...args: any) => {
    const [uid] = args;

    const addContactWindow = new BrowserWindow({
      width: 360,
      height: 623,
      icon: path.join(process.env.VITE_PUBLIC || '', 'logo.jpg'),
      fullscreen: false,
      maximizable: false,
      // transparent: true,//创建一个完全透明的窗口
      titleBarStyle: 'hidden',
      resizable: false,//自动拖动大小
      autoHideMenuBar: true,//隐藏菜单
      hasShadow: true,
      parent: mainWindow, // 设置父窗口
      modal: true, // 设置为模态窗口
      webPreferences: {
        preload: path.join(__dirname, 'preload.mjs'),
        contextIsolation: true,
      },
      frame: false,
    });

    // 保存当前窗口实例
    saveWindow('addContact', mainWindow)

    let loadURL = process.env.VITE_DEV_SERVER_URL || path.join(__dirname, '..', 'dist', 'index.html');
    loadURL = `${loadURL}#/contact/add/${uid}`;
    if (process.env.VITE_DEV_SERVER_URL) {
      addContactWindow.loadURL(loadURL);
    } else {
      addContactWindow.loadFile(loadURL);
    }

    //打开控制台
    if (process.env.NODE_ENV === 'development') {
      addContactWindow.webContents.openDevTools();
    }

  });


  // 处理重新登录
  ipcMain.handle('onReLogin', () => {
    // 窗口变化
    mainWindow.setResizable(true);
    //上面设置了最小窗口大小，所这里需要重新设置窗口大小，否则无法修改大小
    mainWindow.setMinimumSize(LOGIN_WIDTH, LOGIN_HEIGHT);
    mainWindow.setSize(LOGIN_WIDTH, LOGIN_HEIGHT);
    mainWindow.center();
    mainWindow.setResizable(false);

    // 通知渲染进程进行路由跳转
    mainWindow.webContents.send('redirectToLogin');
  });

  return mainWindow;
}
